package com.qiangqiang.adapter;

import com.qiangqiang.bean.TypeAndNameBean;
import com.qiangqiang.entity.Clazs;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by q on 2018/4/6.
 */
public class SqlAdaptee {

    Object setObjectBean(ResultSet resultSet, Class<?> c) {
        Object obj = null;
        List<TypeAndNameBean> list = getType(c);
        try {
            obj = c.newInstance();
            BeanInfo bi = Introspector.getBeanInfo(c);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            resultSet.next();
            for (int i = 0; i < list.size(); i++) {
                for (PropertyDescriptor pd : pds) {
                    if (list.get(i).getName().equals(pd.getName())) {
                        if (list.get(i).getType().equals("int")) {
                            pd.getWriteMethod().invoke(obj, resultSet.getInt(i + 1));
                        } else if (list.get(i).getType().equals("String")) {
                            pd.getWriteMethod().invoke(obj, resultSet.getString(i + 1));
                        }
                    }
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static List<TypeAndNameBean> getType(Class<?> c) {
        List<TypeAndNameBean> list = new ArrayList<TypeAndNameBean>();
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            TypeAndNameBean bean = new TypeAndNameBean(field.getType().getSimpleName(), field.getName());
            list.add(bean);
        }
        return list;
    }

}
